<script setup lang="ts">
import { useUserStore } from '@/store/modules/user';
import { ref } from 'vue'
import axios, { ResponseType } from 'axios';
import { demo } from '@/api';
import { UserRoleReq } from '@/types/user';
// defineProps<{ msg: string }>()

const userStore = useUserStore()
const count = ref(0)
const config = {
  // 默认地址请求地址，可在 .env 开头文件中修改
  baseURL: import.meta.env.VITE_APP_BASE_API as string,
  // 设置超时时间（10s）
  timeout: 10000,
  // 跨域时候允许携带凭证
  withCredentials: true
};
// 创建实例
const service = axios.create(config);

const download = async () => {
  let config = {
    responseType: 'blob' as ResponseType,
    method: "GET",
    // url: '/api/img/bar.jpg',
    url: '/api/prod-api/robot/homePageDevice/getRobotMap?deviceId=0000018e-da85-f2a6-0000-00003c8880b7',
  }
  const res = await service.request(config).then((response) => {
    let { data, config, headers } = response;
    debugger
    console.log('config.responseType', config.responseType, (typeof (data)));
    console.log((data instanceof Blob));
    if (data instanceof Blob) {
      if (data.type.indexOf('application/json') !== -1) {
        return data.text();
      } else {
        let filename = 'test.png';
        const disposition = headers['Content-Disposition'];
        if (disposition && disposition.indexOf('attachment') !== -1) {
          const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
          const matches = filenameRegex.exec(disposition);
          if (matches != null && matches[1]) filename = decodeURI(matches[1].replace(/['"]/g, ''));
        }

        const URL = window.URL || window.webkitURL;
        const downloadUrl = URL.createObjectURL(data);
        const a = document.createElement('a');
        a.href = downloadUrl;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(downloadUrl);
        return "success";
      }
    } else {
      return data;
    }
  }

  );
  console.log("res", res);
};
const getDemo = () => {
  console.log("userStore.token",userStore.token);
  let data: UserRoleReq = { userId: "123" }
  demo(data).catch(err => { 
    console.log("err", err);
  });
};
const refresh = async() => {
  let boolean = await userStore.refresh();
  console.log("vue refresh", boolean);
};
</script>

<template>
  <div class="card">
    <button type="button" @click="getDemo">Save Demo</button>
    <button type="button" @click="refresh">Refresh</button>
  </div>
  <div class="card">
    <button type="button" @click="download">download demo</button>
    <button type="button" @click="count++">count is {{ count }}</button>
    <p>
      Edit
      <code>components/HelloWorld.vue</code> to test HMR
    </p>
  </div>

</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
